// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <melon/init/init.h>
#include <turbo/flags/flag.h>
#include <gtest/gtest.h>

#include <pollux/testing/exec/presto_query_runner.h>
#include <pollux/testing/exec/writer_fuzzer_runner.h>

TURBO_FLAG(int64_t,
    seed,
    0,
    "Initial seed for random number generator used to reproduce previous "
    "results (0 means start with random seed).");

TURBO_FLAG(std::string,
    presto_url,
    "",
    "Presto coordinator URI along with port. If set, we use Presto "
    "source of truth. Otherwise, use DuckDB. Example: "
    "--presto_url=http://127.0.0.1:8080");

TURBO_FLAG(uint32_t,
    req_timeout_ms,
    1000,
    "Timeout in milliseconds for HTTP requests made to reference DB, "
    "such as Presto. Example: --req_timeout_ms=2000");

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);

  // Calls common init functions in the necessary order, initializing
  // singletons, installing proper signal handlers for better debugging
  // experience
  melon::Init init(&argc, &argv);

  kumo::pollux::memory::MemoryManager::initialize({});

  size_t initialSeed = FLAGS_seed == 0 ? std::time(nullptr) : FLAGS_seed;

  using Runner = kumo::pollux::exec::test::WriterFuzzerRunner;
  using PrestoQueryRunner = kumo::pollux::exec::test::PrestoQueryRunner;

  POLLUX_CHECK(
      !FLAGS_presto_url.empty(),
      "Table writer fuzzer only supports presto DB for now");
  std::shared_ptr<kumo::pollux::memory::MemoryPool> rootPool{
      kumo::pollux::memory::memoryManager()->addRootPool()};
  auto queryRunner = std::make_unique<PrestoQueryRunner>(
      rootPool.get(),
      FLAGS_presto_url,
      "writer_fuzzer",
      static_cast<std::chrono::milliseconds>(FLAGS_req_timeout_ms));
  KLOG(INFO) << "Using Presto as the reference DB.";
  return Runner::run(initialSeed, std::move(queryRunner));
}
